package com.speedata.testsimple;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.serialport.SerialPortSpd;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.speedata.MyApp;
import com.speedata.libutils.DataConversionUtils;
import com.speedata.uhftest.R;
import com.speedata.utils.FileUtils;
import com.speedata.utils.Logcat;
import com.speedata.utils.ProgressDialogUtils;
import com.speedata.utils.ToastUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class JungongJieshouActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bt1;
    private Button bt2;
    private Button bt3;
    private Button bt4;
    private EditText et;
    private Button bt5;
    private EditText et2;
    private Button bt6;
    private EditText et3;
    private Button bt7;
    private EditText et4;
    private TextView show;

    private List<String> outList;
    private List<String> inList;

    SerialPortSpd serialPortSpd;
    int fd;
    int dl = 200;
    int jg = 10;
    String ck = "ttyS2";
    int btl = 115200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jungong_jieshou);
        initView();
        initData();
    }

    private void initData() {
        outList = new ArrayList<>();
        inList = new ArrayList<>();

        serialPortSpd = new SerialPortSpd();


    }

    @Override
    protected void onDestroy() {
        try {
            mReadThread.interrupt();
        } catch (Exception e) {
            e.printStackTrace();
        }

        serialPortSpd.CloseSerial(fd);
        super.onDestroy();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        bt1 = findViewById(R.id.bt1);
        bt2 = findViewById(R.id.bt2);
        bt3 = findViewById(R.id.bt3);
        bt4 = findViewById(R.id.bt4);
        et = findViewById(R.id.et);
        et.setText("200");
        bt5 = findViewById(R.id.bt5);
        et2 = findViewById(R.id.et2);
        et2.setText("10");
        bt6 = findViewById(R.id.bt6);
        et3 = findViewById(R.id.et3);
        et3.setText("ttyS2");
        bt7 = findViewById(R.id.bt7);
        et4 = findViewById(R.id.et4);
        et4.setText("115200");

        show = findViewById(R.id.show);


        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
        bt3.setOnClickListener(this);
        bt4.setOnClickListener(this);
        bt5.setOnClickListener(this);
        bt6.setOnClickListener(this);
        bt7.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt1:
                //导入数据
                readFile("1.txt");
                break;
            case R.id.bt2:
                //开始接收
                //sendReceiveData();
                receiveData();
                break;
            case R.id.bt3:
                //数据导出
                outFile();
                break;
            case R.id.bt4:
                //串口延时
                String x = et.getText().toString();
                dl = Integer.parseInt(x);
                ToastUtils.showShortToastSafe("延时设置为：" + dl);
                break;
            case R.id.bt5:
                //间隔时间
                String x1 = et2.getText().toString();
                jg = Integer.parseInt(x1);
                ToastUtils.showShortToastSafe("间隔设置为：" + jg);
                break;
            case R.id.bt6:
                //间隔时间
                String x2 = et3.getText().toString();
                ck = x2;
                ToastUtils.showShortToastSafe("串口为：" + ck);
                break;
            case R.id.bt7:
                //间隔时间
                String x3 = et4.getText().toString();
                btl = Integer.parseInt(x3);
                ToastUtils.showShortToastSafe("波特率为：" + btl);
                break;
            default:
                break;
        }
    }

    private void receiveData() {
        try {
            serialPortSpd.OpenSerial("/dev/" + ck, btl);

            Thread.sleep(jg);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        mReadThread = new ReadThread();
        mReadThread.start();

    }

    /**
     * 循环列表长度的自发自收
     */
    private void sendReceiveData() {

        try {
            serialPortSpd.OpenSerial("/dev/" + ck, btl);

            Thread.sleep(jg);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < inList.size(); i++) {

            testOut(inList.get(i));

            try {
                //Thread.sleep(100);
                Thread.sleep(jg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        serialPortSpd.CloseSerial(fd);
    }


    /**
     * 检测串口
     * 打开串口0  自环数据收发   数据一致为正确
     */
    @SuppressLint("SetTextI18n")
    private void testOut(String msg) {
        String sentData = msg;

        try {

            byte[] bytes = sentData.getBytes(StandardCharsets.UTF_8);
            fd = serialPortSpd.getFd();
            serialPortSpd.WriteSerialByte(fd, bytes);

            byte[] readData = serialPortSpd.ReadSerial(fd, bytes.length, dl);
            if (readData == null) {
                Logcat.d("FAILED" + "\n");
                return;
            }
            String readString = DataConversionUtils.byteArrayToAscii(readData);
            outList.add(readString);

        } catch (Exception e) {
            e.printStackTrace();
            Logcat.d("FAILED" + "\n");
        }

    }


    private void readFile(final String txtName) {

        ProgressDialogUtils.showProgressDialog(this, "导入1.txt的数据");

        new Thread(() -> {
            final int acount = FileUtils.importTxtFile(txtName);
            Message msg = new Message();
            msg.obj = acount;
            handler.sendMessage(msg);
        }).start();

    }

    private void outFile() {
        mReadThread.interrupt();
        serialPortSpd.CloseSerial(fd);
        ProgressDialogUtils.showProgressDialog(this, "导出数据");

        try {
            FileUtils fileUtils = new FileUtils();
            int h = fileUtils.outputfile(getOutputList(), createFilename());
            if (h == 1) {
                ToastUtils.showShortToastSafe("导出数据2.txt到根目录下完成");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        ProgressDialogUtils.dismissProgressDialog();
    }

    //创建导出文件的名字
    @SuppressLint("SdCardPath")
    public String createFilename() throws IOException {
        return "/sdcard/" + "2.txt";
    }

    //得到需要导出的文件List
    public List<String> getOutputList() {
        //return inList;
        return outList;
    }

    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ProgressDialogUtils.dismissProgressDialog();
            int count = (int) msg.obj;
            if (count == -1) {
                new AlertDialog.Builder(JungongJieshouActivity.this).setTitle("错误").setMessage("空数据文件").show();
                return;
            }

            inList = MyApp.getInstance().getmList();
            Toast.makeText(JungongJieshouActivity.this, "总数量:" + MyApp.getInstance().getmList().size(), Toast.LENGTH_SHORT).show();
        }
    };


    private ReadThread mReadThread;
    private String readstr = "";
    private byte[] tmpbuf = new byte[1024];
    private int readed = 0;

    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                try {
                    try {
                        tmpbuf = serialPortSpd.ReadSerial(fd, 2048, dl);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if (tmpbuf != null) {
                        readed = tmpbuf.length;
                        byte[] readbuf = new byte[readed];
                        System.arraycopy(tmpbuf, 0, readbuf, 0, readed);

                        readstr = DataConversionUtils.byteArrayToAscii(readbuf);
                        //为扫描结果添加已经存储的前后缀

                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = readstr;
                        handler2.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();

                }
            }
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler2 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                try {
                    outList.add(String.valueOf(msg.obj));

                    runOnUiThread(() -> show.setText(outList.get(outList.size() - 1)));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

}